package com.erp.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.erp.product.dao.CategoryDao;
import com.erp.product.entity.CategoryEntity;
import com.erp.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 查询所有分类
        List<CategoryEntity> allCategory = this.baseMapper.selectList(null);
        // 组装成父子结构
        List<CategoryEntity> root=allCategory.stream().filter(c->{
            return c.getParentCid()==0;
        }).map(c->{
            c.setChildren(findChildrenCategory(allCategory,c));
            return c;
        }).collect(Collectors.toList());
        return allCategory;
    }

    private List<CategoryEntity> findChildrenCategory(List<CategoryEntity> allCategory, CategoryEntity entity) {
        List<CategoryEntity> child=allCategory.stream().filter(c->{
            return c.getParentCid()==entity.getCatId();
        }).map(c->{
            c.setChildren(findChildrenCategory(allCategory,c));
            return c;
        }).collect(Collectors.toList());
        return child;
    }

}